package com.efuture.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassNAME ObjectOutputStreamTest
 * @Description 该类主要用于实现序列化
 * @Author zhaoshanshan
 * @Date 2021/9/8 8:51 下午
 * @Version 1.0
 */
public class ObjectOutputStreamTest {

    public static void main(String[] args) {
        ObjectOutputStream ois = null;
        try {
            //序列化一个对象
//            Student s1 = new Student(1,"yifan");
//            ois = new ObjectOutputStream(new FileOutputStream("javasestudy/src/com.efuture.io/xuliehua"));
//            ois.writeObject(s1);

            //序列化多个对象
            Student s1 = new Student(1,"yifan");
            Student s2 = new Student(2,"tongshuai");
            Student s3 = new Student(3,"shanshan");
            ois = new ObjectOutputStream(new FileOutputStream("javasestudy/src/com.efuture.io/xuliehua"));
            List arrayList = new ArrayList<>();
            arrayList.add(s1);
            arrayList.add(s2);
            arrayList.add(s3);
            ois.writeObject(arrayList);
            ois.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
           if(null!=ois){
               try {
                   ois.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
               ;
           }
        }
    }


}
class Student implements Serializable {//必须实现Serializable接口才能实现序列化
    //序列化版本号 如果不手动写，虚拟机会自动创建一个序列化版本号
    //但是如果不手动写的话，后期代码有修改的话，序列化会出现问题
    private static final long serialVersionUID = 1L;

    private int no;
    private  String name;
    public Student(int no,String name){
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "no="+this.no+"  name="+this.name;
    }
}